<!-- eslint-disable @typescript-eslint/no-misused-promises -->
<!-- eslint-disable @typescript-eslint/no-floating-promises -->
<script setup lang="ts">
  import { ref, h, watch } from 'vue'
  import {
    NDatePicker,
    NInput,
    NIcon,
    NDataTable,
    NPagination,
    type DataTableRowKey,
    useMessage,
    NButton,
  } from 'naive-ui'
  import {
    CheckCircleFilled,
    CancelFilled,
    MoreHorizFilled,
    AccessTimeOutlined,
  } from '@vicons/material'
  import { deleteScheme, downloadScheme, getSchemeList, updateSchemeName } from '@/api/scheme'
  import dayjs from 'dayjs'
  import SvgIcon from '@/components/SvgIcon/index.vue'
  import { useRoute, useRouter } from 'vue-router'
  import DeleteModal from '@/components/common/DeleteModal/index.vue'
  const props = defineProps<{
    categoryType: string | number
  }>()

  const route = useRoute()
  const id = route.params.id as string
  const message = useMessage()
  const getList = async () => {
    const startTime = date.value ? dayjs(date.value[0]).format('YYYY-MM-DD 00:00:00') : undefined
    const endTime = date.value ? dayjs(date.value[1]).format('YYYY-MM-DD 23:59:59') : undefined
    const res = await getSchemeList({
      pageNum: page.value,
      pageSize: pageSize.value,
      startTime,
      endTime,
      schemeName: docName.value,
      libraryType: id,
      categoryType: props.categoryType,
    })
    res.list.forEach((item: any) => {
      item.isEdit = false
      item.initialName = item.schemeName
    })
    itemCount.value = res.total
    dataSource.value = res.list
  }

  const date = ref(null)
  const docName = ref(undefined)
  const deleteDocList = ref<DataTableRowKey[]>([])
  const handleDeleteDoc = () => {
    if (deleteDocList.value.length === 0) return
    deleteIds.value = []
    deleteDocList.value.forEach(item => {
      deleteIds.value.push(item.toString())
    })
    deleteModalRef.value?.showModal(`确定要删除选中文档吗？`)
  }
  // 分页
  const page = ref(1)
  const pageSize = ref(10)
  const itemCount = ref(0)

  const handleUpdatePageSize = async (_pageSize: number) => {
    pageSize.value = _pageSize
    page.value = 1
    await getList()
  }

  const handleUpdatePage = async (_page: number) => {
    page.value = _page
    await getList()
  }

  const rowKey = (row: any) => {
    return row.id
  }

  const handleCheck = (keys: DataTableRowKey[]) => {
    deleteDocList.value = keys
  }

  const columns = ref<any[]>([
    {
      type: 'selection',
    },
    {
      title: '文档名称',
      key: 'schemeName',
      minWidth: 300,
      render: (row: { schemeName: string; isEdit: boolean; initialName: string; id: string }) => {
        return h('div', { class: 'flex items-center gap-1' }, [
          row.isEdit
            ? h(NInput, {
                value: row.schemeName,
                onUpdateValue(v) {
                  row.schemeName = v
                },
                onKeydown: (e: any) => {
                  if (e.key === 'Enter') {
                    if (row.schemeName.trim().length === 0) return message.error('方案名称不能为空')
                    updateSchemeName({
                      id: row.id,
                      shemeName: row.schemeName,
                    }).then(() => {
                      message.success('编辑方案名称成功')
                      row.isEdit = false
                      row.initialName = row.schemeName
                    })
                  } else if (e.key === 'Escape') {
                    row.schemeName = row.initialName
                    row.isEdit = false
                  }
                },
                maxlength: 100,
                clearable: true,
                onBlur: () => {
                  row.schemeName = row.initialName
                  row.isEdit = false
                },
              })
            : h('div', { class: 'text-[14px] leading-9 ml-2' }, row.schemeName),
          row.isEdit
            ? null
            : h(SvgIcon, {
                class: 'text-[14px] leading-9 ml-2 cursor-pointer',
                name: 'file-edit',
                onClick: () => (row.isEdit = true),
              }),
        ])
      },
    },
    {
      title: '文件大小',
      key: 'fileSize',
    },
    {
      title: '更新时间',
      key: 'updateTime',
    },
    {
      title: '生成时间',
      key: 'createTime',
    },
    {
      title: '审核结果',
      key: 'result',
      render: (row: { status: string }) => {
        let icon, text, color, bgColor
        if (+row.status === 0) {
          return h('div', { class: 'flex items-center gap-1' }, [
            h('div', {
              class: 'w-[6px] h-[6px] rounded-full bg-[#F5222D]',
            }),
            h('div', { class: 'text-[14px] leading-9 ml-2' }, '未提交'),
          ])
        }
        if (+row.status === 2) {
          icon = CheckCircleFilled
          text = '审核通过'
          color = '#00B42A'
          bgColor = '#E8FFEA'
        } else if (+row.status === 3) {
          icon = CancelFilled
          text = '审核未通过'
          color = '#F5222D'
          bgColor = '#FFECE8'
        } else {
          icon = MoreHorizFilled
          text = '未审核'
          color = '#F77234'
          bgColor = '#FFF1EB'
        }
        return h(
          'div',
          {
            class: 'flex items-center w-fit gap-1 rounded px-2 h-[20px] leading-[20px] text-[12px]',
            style: {
              backgroundColor: bgColor,
            },
          },
          [
            h(
              NIcon,
              {
                size: 16,
                color,
                class:
                  +row.status === 0 || +row.status === 1
                    ? 'rounded-full bg-[#F77234] !text-[#fff] !text-[14px]'
                    : '',
              },
              { default: () => h(icon) }
            ),
            h('div', { style: { color } }, text),
          ]
        )
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (row: {
        schemeUrl: string
        id: string
        status: string
        schemeName: string
        schemeId: string
      }) => {
        return h('div', { class: 'flex items-center' }, [
          h(
            NButton,
            { quaternary: true, type: 'info', class: '!px-2', onClick: (): any => handleView(row) },
            { default: () => '查看' }
          ),
          h(
            NButton,
            {
              quaternary: true,
              type: 'info',
              class: '!px-2',
              disabled: +row.status !== 2,
              onClick: () => handleDownload(row),
            },
            { default: () => '下载' }
          ),
          h(
            NButton,
            {
              quaternary: true,
              type: 'info',
              class: '!px-2',
              onClick: () => beforeHandleDelete(row),
            },
            { default: () => '删除' }
          ),
        ])
      },
    },
  ])
  const router = useRouter()
  const dataSource = ref([])
  const deleteModalRef = ref()
  const deleteIds = ref<string[]>([])
  const beforeHandleDelete = (row: { id: string; schemeName: string }) => {
    deleteIds.value = [row.id]
    deleteModalRef.value?.showModal(`确定要删除文档“${row.schemeName}”吗？`)
  }

  const handleView = (row: { schemeUrl: string; id: string; status: string }) => {
    // 审核通过
    if (+row.status === 2)
      return router.push({ path: `/createAuditPass/${row.id}/1`, query: { libId: id } })
    // 审核未通过
    if (+row.status === 3)
      return router.push({ path: `/createAuditPass/${row.id}/4`, query: { libId: id } })
    // 待审核
    if (+row.status === 1)
      return router.push({ path: `/createAuditPass/${row.id}/3`, query: { libId: id } })
  }

  const handleDownload = async (row: { schemeUrl: string; id: string; schemeName: string }) => {
    // window.open(row.schemeUrl, '_blank')
    const res = await downloadScheme({ id: row.id, schemeName: row.schemeName })
    const blob = new Blob([res], { type: 'application/docx' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${row.schemeName}.docx`
    a.click()
    URL.revokeObjectURL(url)
  }
  const handleDelete = () => {
    deleteScheme({ ids: deleteIds.value.join(',') }).then(() => {
      message.success('删除成功')
      getList()
      deleteIds.value = []
    })
  }

  const handleChange = async () => {
    page.value = 1
    pageSize.value = 10
    await getList()
  }

  watch(
    () => props.categoryType,
    async () => {
      if (props.categoryType) {
        await getList()
      }
    },
    { immediate: true }
  )
</script>

<template>
  <div class="flex-1 h-full flex flex-col gap-6 category-table">
    <div class="h-8 leading-8 flex items-center justify-between">
      <div class="flex items-center gap-4">
        <div class="flex items-center">
          <div class="text-[#4A5055]">时间：</div>
          <div class="flex items-center">
            <n-date-picker
              v-model:value="date"
              type="daterange"
              @update:value="handleChange"
              size="small"
              class="w-[400px]"
              clearable
            >
              <template #date-icon>
                <n-icon :size="16">
                  <AccessTimeOutlined />
                </n-icon>
              </template>
            </n-date-picker>
          </div>
        </div>
        <div class="flex items-center">
          <div class="text-[#4A5055]">文档名称：</div>
          <div class="flex items-center">
            <n-input
              class="!w-[240px]"
              v-model:value="docName"
              placeholder="请输入文档名称"
              size="small"
              @keydown.enter="handleChange"
            />
          </div>
        </div>
      </div>
      <div
        @click="handleDeleteDoc"
        :class="{
          '!cursor-not-allowed': deleteDocList.length === 0,
        }"
        class="px-4 cursor-pointer rounded border border-[#F5222D] text-[#F5222D] bg-[#FFECE8] hover:bg-[#FFECE850] hover:text-[#F5222D50] hover:border-[#F5222D50]"
      >
        批量删除
      </div>
    </div>
    <div class="h-[calc(100%-76px)]">
      <n-data-table
        class="max-h-[calc(100%-56px)] overflow-y-auto"
        :columns="columns"
        :data="dataSource"
        :pagination="false"
        :bordered="false"
        :row-key="rowKey"
        @update:checked-row-keys="handleCheck"
      />
      <div class="h-8 mt-6 flex justify-between items-center">
        <div class="pingfang">
          {{ `已选中 ${deleteDocList.length} 项` }}
        </div>
        <n-pagination
          show-quick-jumper
          v-model:page="page"
          :page-size="pageSize"
          :item-count="itemCount"
          :page-sizes="[10, 20, 50]"
          show-size-picker
          :on-update-page-size="handleUpdatePageSize"
          :on-update-page="handleUpdatePage"
        >
          <template #prefix="{ itemCount }">
            <span class="pingfang text-[#666D7A]">共 {{ itemCount }} 条</span>
          </template>
          <template #suffix>
            <span class="pingfang text-[#666D7A]">页</span>
          </template>
        </n-pagination>
      </div>
    </div>
    <DeleteModal @close="deleteIds = []" ref="deleteModalRef" @submit="handleDelete" />
  </div>
</template>
